﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.GridPerson;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MD5Hash;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.GridPerson
{
    /// <summary>
    /// 更新网格人员的中介者处理类
    /// </summary>
    public class  UpdateGridPersonHandler: IRequestHandler<UpdateGridPersonCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 通过构造函数注入仓储和automapper
        /// </summary>
        /// <param name="accRepo">仓储</param>
        /// <param name="mapper">automapper</param>
        public UpdateGridPersonHandler(IBaseRepository<AccountModel> accRepo,IMapper mapper)
        {
            this.accRepo = accRepo;
            this.mapper = mapper;
        }
        /// <summary>
        ///  更新网格人员的中介者处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>异步的响应包装类</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UpdateGridPersonCommand request, CancellationToken cancellationToken)
        {

            ApiResult<int> result = new ApiResult<int>();//实例化的响应包装类

            //查询数据库里除了自己以为,是否还有相同的名字
            var accountCount = accRepo.GetAll().Where(x=>x.Name==request.Name&&x.Id!=request.Id).Count();
            if (accountCount > 0) {
                result.Code = ApiEnums.Error;
                result.Msg = "系统里已有相同的用户名!";
                result.Data = 0;
                return Task.FromResult(result);
            }

            var model = accRepo.GetModel(request.Id);
            if (model == null) {
                result.Code = ApiEnums.Error;
                result.Msg = "您要修改的账号不存在!";
                result.Data = 0;
                return Task.FromResult(result);
            }

            //如果你填了密码,我就改你的密码.如果没有填写密码,密码不改,还是原来的.
            if (request.Pass.Length < 1)
            {
                request.Pass = model.Pass;
            }
            else { 
            request.Pass = request.Pass.GetMD5(); //修改的时候也要给密码加密
            }
            model = mapper.Map(request,model);//把request参数里的值全部赋值给model
            var r = accRepo.Update(model);

            if (r > 0)
            {
                result.Code = ApiEnums.Success;
                result.Msg = "修改账号成功!";
                result.Data = r;

            }
            else
            {
                result.Code = ApiEnums.Fail;
                result.Msg = "修改账号失败!";
                result.Data = r;
            }


            return Task.FromResult(result);
        }
    }
}
